import React, { useState, useEffect } from 'react';
import { Slide } from './Slide';
import IconFont from '../../iconfont';
import './index.less';
interface CarouselProps {
  slides: Slide[];
  style?: React.CSSProperties;
}

export interface Slide {
  id: number;
  image: string;
  caption: string;
  active?: boolean;
  url?: URL;
}

const Carousel: React.FC<CarouselProps> = ({ slides, style }) => {
  const [currentSlide, setCurrentSlide] = useState(0);

  const handleNext = () => {
    if (currentSlide === slides.length - 1) {
      setCurrentSlide(0);
    } else {
      setCurrentSlide(currentSlide + 1);
    }
  };

  const handlePrev = () => {
    if (currentSlide === 0) {
      setCurrentSlide(slides.length - 1);
    } else {
      setCurrentSlide(currentSlide - 1);
    }
  };

  useEffect(() => {
    const timer = setInterval(() => {
      handleNext();
    }, 4000);
    return () => clearInterval(timer);
  }, [currentSlide]);

  return (
    <div className="carousel-container" style={style}>
      <div className="slides-container">
        {slides.map((slide, index) => (
          <Slide
            key={slide.id}
            image={slide.image}
            caption={slide.caption}
            active={index === currentSlide}
            url={slide.url}
          />
        ))}
      </div>
      <div className="btn-container">
        <IconFont
          className="btn btn-left"
          name="chevron-left"
          onClick={handlePrev}
          size={36}
          color={'gray'}
        />
        <IconFont
          className="btn btn-right"
          name="chevron-right"
          onClick={handleNext}
          size={36}
          color={'gray'}
        />
      </div>
    </div>
  );
};
export default Carousel;
